// order-detail
const app = getApp();
import { PACKAGE_ORDER_PAGE, PACKAGE_ACTIVITY_PAGE } from '../../../constants/route';
import { handleOrderStatus } from '../../biztools/order';
import { TARGET_TYPE } from '../../../constants/common';
import { ORDER_STATUS, ORDER_OWNER_TYPE, ORDER_TYPE } from '../../../constants/order';
import { MESSAGE_ID } from '../../../constants/message';
import { TipDialog } from '../../../common/tip';
import { navTo, showLoading, hideLoading, subscribeMessage } from '../../../common/env';
import { invokePlatformPay } from '../../../common/pay';
import { getOrderDetail, payOrder, cancelOrder, confirmExpressOrder, confirmPickupOrder } from '../../api/order';
import { OrderDetailMixins } from '../../../behaviors/page';
import { setAfterSaleOrderInfo } from '../../../biztools/wex';
let showPaySuccess;

Page({
    mixins: [OrderDetailMixins],
    data: {
        targetType: TARGET_TYPE,
        orderType: ORDER_TYPE,
        orderOwnerType: ORDER_OWNER_TYPE,
        orderDetail: {},
        orderStatusInfo: {},
        activityUrl: '',
    },
    onLoad: async function (options) {
        if (!app.globalData.isReadyAuth) {
            const _ = this;
            const originFunc = app.userIdentifyCallback;
            app.userIdentifyCallback = function (...args) {
                _.onLoad(...args);
                return originFunc && originFunc(...args);
            }
            return;
        } else {
            const { orderNumber } = options;
            showPaySuccess = options.showPaySuccess;
            await this.refreshOrderDetail(orderNumber);
            this.showPaySuccessAction();
        }
    },
    showPaySuccessAction() {
        if (!showPaySuccess) return;
        // todo弹窗
        showPaySuccess = false;
    },
    refreshOrderDetail: async function (orderNumber) {
        showLoading('加载中...');
        console.log('OrderDetail => 订单号为：', orderNumber);
        const orderDetail = await getOrderDetail(orderNumber);
        console.log('OrderDetail => 订单详情为：', orderDetail);
        this.setData({
            orderDetail,
            orderStatusInfo: handleOrderStatus(orderDetail),
            activityUrl: `${PACKAGE_ACTIVITY_PAGE['detail']}?activityId=${orderDetail.activityId}`,
        });
        hideLoading();
    },
    // 订单支付
    invokePayAction: async function () {
        const { serialNumber, amount } = this.data.orderDetail;
        const res = await payOrder(serialNumber, { amount });
        console.log('OrderList => 订单支付结果：', serialNumber, res);
        if (res) {
            await invokePlatformPay(res.transactionInfo);
            await this.refreshOrderDetail(serialNumber);
            await subscribeMessage([MESSAGE_ID.order_status, MESSAGE_ID.self_pickup]);
            showPaySuccess = true;
            this.showPaySuccessAction();
        }
    },
    // 确认收货
    invokeExpressConfirm: async function (event) {
        const { serialNumber } = this.data.orderDetail;
        const _ = this;
        TipDialog({
            title: '确认收货',
            message: '请确认您已经收到了货物',
            confirmButtonText: '确定收货',
            ok: async () => {
                const res = await confirmExpressOrder(serialNumber);
                console.log('OrderDetail => 订单确认收货结果：', serialNumber, res);
                if (res) {
                    await _.refreshOrderDetail(serialNumber);
                }
            },
        });
    },
    // 确认提货
    invokePickupConfirm: async function (event) {
        const { serialNumber } = this.data.orderDetail;
        const _ = this;
        TipDialog({
            title: '确认提货',
            message: '请确认您已经提取了货物',
            confirmButtonText: '确定提货',
            ok: async () => {
                const res = await confirmPickupOrder(serialNumber);
                console.log('OrderDetail => 订单确认提货结果：', serialNumber, res);
                if (res) {
                    await _.refreshOrderDetail(serialNumber);
                }
            },
        });
    },
    // 取消订单
    invokeCancelOrder: function () {
        // 根据是否支付，来走取消，还是售后
        const { orderDetail } = this.data;
        const { serialNumber, orderStatus } = orderDetail;
        const _ = this;
        TipDialog({
            title: '取消订单',
            message: '您确定取消本次订单吗？',
            ok: async () => {
                // 判断是否能够直接取消
                if (orderStatus === ORDER_STATUS.ORDER_NEED_PAY) {
                    console.log('OrderDetail => 直接取消订单');
                    const res = await cancelOrder(serialNumber);
                    if (res) {
                        await _.refreshOrderDetail(serialNumber);
                    }
                } else {
                    console.log('OrderDetail => 售后取消订单');
                    setAfterSaleOrderInfo(orderDetail);
                    navTo(PACKAGE_ORDER_PAGE.orderCancel);
                }
            },
        });
    },
    // 售后
    afterSale: function (event) {
        const itemInfo = event.detail;
        // 跳转到选择售后类型
        setAfterSaleOrderInfo(this.data.orderDetail);
        navTo(PACKAGE_ORDER_PAGE.orderAfterSaleType, {
            goodsId: itemInfo.orderDetailId,
        });
    },
})